const app = getApp()

Page({
    data: {
        product: null,
        meetingInfo: {
            location: '',
            time: ''
        },
        contactInfo: {
            phone: '',
            wechat: ''
        },
        formatMeetingTime: '',
        showLocationPicker: false,
        showTimePicker: false,
        locationOptions: [
            '第一教学楼门口',
            '第二教学楼门口',
            '图书馆一楼大厅',
            '学生活动中心',
            '校园超市门口',
            '食堂一楼',
            '食堂二楼',
            '宿舍楼下'
        ],
        currentDate: new Date().getTime(),
        minDate: new Date().getTime(),
        maxDate: new Date().getTime() + 7 * 24 * 60 * 60 * 1000, // 最多预约7天后
        submitting: false
    },

    onLoad(options) {
        const { productId } = options
        if (productId) {
            this.loadProductInfo(productId)
        }

        // 尝试获取用户缓存的联系方式
        const userInfo = wx.getStorageSync('userInfo')
        if (userInfo) {
            this.setData({
                'contactInfo.phone': userInfo.phone || '',
                'contactInfo.wechat': userInfo.wechat || ''
            })
        }
    },

    // 加载商品信息
    async loadProductInfo(productId) {
        try {
            const res = await new Promise((resolve, reject) => {
                wx.request({
                    url: `${app.globalData.baseUrl}/api/products/${productId}`,
                    method: 'GET',
                    header: {
                        'Authorization': `Bearer ${wx.getStorageSync('token')}`
                    },
                    success: (res) => resolve(res),
                    fail: (err) => reject(err)
                })
            })
            console.log(res)
            if (res.statusCode === 200 && res.data.success) {
                this.setData({
                    product: res.data.data.product
                })
            } else {
                throw new Error(res.data.message || '获取商品信息失败')
            }
        } catch (error) {
            console.error('获取商品信息失败：', error)
            wx.showToast({
                title: '获取商品信息失败',
                icon: 'none'
            })
        }
    },

    // 显示地点选择器
    showLocationPicker() {
        this.setData({ showLocationPicker: true })
    },

    // 关闭地点选择器
    onLocationPickerClose() {
        this.setData({ showLocationPicker: false })
    },

    // 确认地点选择
    onLocationPickerConfirm(event) {
        this.setData({
            'meetingInfo.location': event.detail.value,
            showLocationPicker: false
        })
    },

    // 显示时间选择器
    showTimePicker() {
        this.setData({ showTimePicker: true })
    },

    // 关闭时间选择器
    onTimePickerClose() {
        this.setData({ showTimePicker: false })
    },

    // 确认时间选择
    onTimePickerConfirm(event) {
        const date = new Date(event.detail)
        this.setData({
            'meetingInfo.time': date.toISOString(),
            formatMeetingTime: this.formatDateTime(date),
            showTimePicker: false
        })
    },

    // 格式化日期时间
    formatDateTime(date) {
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        const hour = date.getHours().toString().padStart(2, '0')
        const minute = date.getMinutes().toString().padStart(2, '0')
        return `${year}-${month}-${day} ${hour}:${minute}`
    },

    // 手机号输入处理
    onPhoneChange(event) {
        this.setData({
            'contactInfo.phone': event.detail
        })
    },

    // 微信号输入处理
    onWechatChange(event) {
        this.setData({
            'contactInfo.wechat': event.detail
        })
    },

    // 表单验证
    validateForm() {
        const { meetingInfo, contactInfo } = this.data

        if (!meetingInfo.location) {
            wx.showToast({
                title: '请选择见面地点',
                icon: 'none'
            })
            return false
        }

        if (!meetingInfo.time) {
            wx.showToast({
                title: '请选择见面时间',
                icon: 'none'
            })
            return false
        }

        if (!contactInfo.phone) {
            wx.showToast({
                title: '请输入手机号码',
                icon: 'none'
            })
            return false
        }

        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(contactInfo.phone)) {
            wx.showToast({
                title: '请输入有效的手机号码',
                icon: 'none'
            })
            return false
        }

        if (!contactInfo.wechat) {
            wx.showToast({
                title: '请输入微信号',
                icon: 'none'
            })
            return false
        }

        return true
    },

    // 提交订单
    async submitOrder() {
        if (!this.validateForm()) return;
        if (this.data.submitting) return;

        this.setData({ submitting: true });

        try {
            const orderData = {
                productId: this.data.product._id,
                meetingInfo: this.data.meetingInfo,
                contactInfo: this.data.contactInfo
            };

            const res = await new Promise((resolve, reject) => {
                wx.request({
                    url: `${app.globalData.baseUrl}/api/orders`,
                    method: 'POST',
                    header: {
                        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
                        'Content-Type': 'application/json'
                    },
                    data: orderData,
                    success: (res) => resolve(res),
                    fail: (err) => reject(err)
                });
            });

            console.log('提交订单响应:', res);

            if ((res.statusCode === 200 || res.statusCode === 201) && res.data.success) {
                // 缓存联系方式
                const userInfo = wx.getStorageSync('userInfo') || {};
                userInfo.phone = this.data.contactInfo.phone;
                userInfo.wechat = this.data.contactInfo.wechat;
                wx.setStorageSync('userInfo', userInfo);

                wx.showToast({
                    title: '订单提交成功',
                    icon: 'success',
                    duration: 2000,
                    success: () => {
                        setTimeout(() => {
                            // 跳转到订单详情页
                            wx.redirectTo({
                                url: `/pages/order/detail/detail?id=${res.data.data.order._id}`
                            });
                        }, 2000);
                    }
                });
            } else {
                throw new Error(res.data.message || '提交订单失败');
            }
        } catch (error) {
            console.error('提交订单失败：', error);
            wx.showToast({
                title: error.message || '提交订单失败',
                icon: 'none'
            });
        } finally {
            this.setData({ submitting: false });
        }
    }
}) 